package com.example.javademo.Service;

import com.example.javademo.Entity.User;
import com.example.javademo.Mapper.UserAuthMapper;
import com.example.javademo.Utils.JwtUtils;
import com.example.javademo.Utils.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserAuthService {
    //注册接口
    @Autowired
    private UserAuthMapper userAuthMapper;
    public Response register(User userRequest){
        //TODO:注册接口
        if(userAuthMapper.checkUsernameExists(userRequest)){
            System.out.println("User already exists");
            return Response.errorMsg("昵称已被占用");
        }
        else{
            userAuthMapper.register(userRequest);
            return Response.okMsg("注册成功",null);
        }
    }

    public Response login(User userRequest) {
        if(userAuthMapper.checkUsernameExists(userRequest)){
        System.out.println("Use------"+userAuthMapper.login(userRequest));
            User user = userAuthMapper.login(userRequest);
            if(user != null){
                Map<String,Object> map = new HashMap<String,Object>();
                map.put("username",user.getUsername());
                String token = JwtUtils.createToken(map);
                return Response.okMsg("登录成功",token);
            }
            else{
                return Response.errorMsg("密码错误");
            }
        }
        else{
            return Response.errorMsg("用户不存在");
        }
    }
}
